import { defineStore } from 'pinia'
import {
  getArticleRequest,
  getArticleByCategoryIdRequest
} from '@/api/public/index.js'
const useCardListStore = defineStore('cardList', {
  state: () => ({
    photoData: [],
    MbData: [],
    isLoad: true,
    currentPage: 1,
    size: 20,
    //图片放大组件需要的数据
    renderValue: {
      src: '',
      position: '',
      show: false
    }
  }),
  actions: {
    getCurrentPageData() {
      if (this.isLoad) {
        getArticleRequest(this.currentPage, this.size).then((res) => {
          if (res.data.length === 0) {
            this.isLoad = false
          } else {
            this.photoData = [...this.photoData, ...res.data]
            this.currentPage++
          }
        })
      }
    },
    //根据分类id获取对应的文章
    async getArticleByCategoryId(id) {
      const result = await getArticleByCategoryIdRequest(id)
      this.MbData = result.data.categoryArticles
    },
    //控制图片放大组件展示
    showPhotoComponent(renderValue) {
      //解构
      const { src, show, position } = renderValue
      this.renderValue = {
        src,
        show,
        position
      }
    }
  },
  getters: {
    getCurrentArticle: (state) => (id) => {
      // 从 localStorage 获取当前文章
      const cachedArticle = localStorage.getItem('currentArticle')
        ? JSON.parse(localStorage.getItem('currentArticle'))
        : null
      // 如果本地存储中已有文章并且 ID 匹配，直接返回
      if (cachedArticle && cachedArticle.id === Number(id)) {
        //强制更改数据触发dom更新查找当前文章在整个文章数据中的下标
        return cachedArticle
      }
      // 查找 photoData 中的当前文章
      const currentArticle = state.photoData.find(
        (item) => item.id == Number(id)
      )
      if (currentArticle) {
        localStorage.setItem('currentArticle', JSON.stringify(currentArticle))
      }
      return currentArticle
    }
  }
})
export default useCardListStore
